package com.br.fmn.clubedoimovel.negocio.servico;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import android.app.ProgressDialog;
import android.os.AsyncTask;

import com.br.fmn.clubedoimovel.negocio.entidade.Coordinates;
import com.br.fmn.clubedoimovel.negocio.map.RouteOverlay;
import com.br.fmn.clubedoimovel.negocio.util.StringUtil;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;

public class RoutAsyncTask extends
		AsyncTask<Coordinates, Void, Collection<GeoPoint>> {

	private ProgressDialog dialog;
	private MapView mapView;

	public RoutAsyncTask(MapView mapa) {
		mapView = mapa;
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		dialog = ProgressDialog.show(mapView.getContext(), "Aguarde",
				"Calculando rota...");
	}

	@Override
	protected void onPostExecute(Collection<GeoPoint> result) {
		super.onPostExecute(result);

		if (result != null) {

			// Pega o GeoPoint do meio da lista p/ dar zoom
			List<GeoPoint> geoPoinst = new ArrayList<GeoPoint>(result);
			GeoPoint midCoordinate = geoPoinst.get(geoPoinst.size() / 2);

			// Cria o Overlay que vai desenhar a Rota
			RouteOverlay overlay = new RouteOverlay(result);
			mapView.getOverlays().add(overlay);

			// Centraliza no meio da rota
			mapView.getController().animateTo(midCoordinate);
		}
		dialog.dismiss();
	}

	/**
	 * recupera os Geopoints de parser do XML.
	 * 
	 * @param inputStream
	 * @return
	 * @throws SAXException
	 * @throws IOException
	 * @throws ParserConfigurationException
	 */
	private List<GeoPoint> getGeoPoints(InputStream inputStream)
			throws SAXException, IOException, ParserConfigurationException {

		Document xmlMap = XMLParsable.createXML(inputStream);
		List<GeoPoint> geoPoints = XMLParsable.searchTAGGeoPoint(xmlMap);

		return geoPoints;

	}

	@Override
	protected Collection<GeoPoint> doInBackground(Coordinates... coordinates) {

		String urlRout = StringUtil.urlRout(coordinates);

		// Obtendo a lista de GeoPoints
		InputStream dateConnection;
		try {

			dateConnection = ConnectionManager.retrieveConnection(urlRout)
					.getInputStream();
			return getGeoPoints(dateConnection);

		} catch (IOException e) {
			e.printStackTrace();

		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();

		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;

	}

}
